<?php

	require_once(dirname(__FILE__).'/class.adminview.php');

	class AKB_COMMENT extends AdminView
	{
		/**
		* @var string $query The sql used to display the list of comments
		*/
		var $query = '';

		/**
		* @var string $countQuery The sql used to work out the number of
		* comments that running $this->query is going to display
		*/
		var $countQuery = '';

		/**
		* HandlePage
		*
		* Handles page routing based on the current ToDo get string
		* @return void
		*/
		function HandlePage()
		{
			$GLOBALS['Message'] = '';

			if (isset($_GET['ToDo'])) {
				switch (strtolower($_GET['ToDo'])) {
					case 'advcommentsearch':
						if ($_SESSION['user']->verify('comment', 'edit')
						|| $_SESSION['user']->verify('comment', 'delete')) {
							$this->ShowAdvancedSearch();
						} else {
							$this->NoPermission();
						}
					break;
					case 'deletecomment':
						if ($_SESSION['user']->verify('comment', 'edit')
						|| $_SESSION['user']->verify('comment', 'delete')) {
							$this->DeleteComment();
						} else {
							$this->NoPermission();
						}
					break;
					case 'updatecommentstatus':
						if ($_SESSION['user']->verify('comment', 'edit')) {
							$this->UpdateStatus();
						} else {
							$this->NoPermission();
						}
					break;
					case 'viewcomments':
					default:
						if ($_SESSION['user']->verify('comment', 'edit')
						|| $_SESSION['user']->verify('comment', 'delete')) {
							if (isset($_POST['bulkaction'])) {
								$this->BulkAction();
							}
							$this->ShowCommentList();
						} else {
							$this->NoPermission();
						}
				}
			}
		}

		/**
		* BulkAction
		*
		* The handler for performing an action to multiple items
		* @return void
		*/
		function BulkAction()
		{
			if (!isset($_POST['bulkaction'])) {
				return false;
			}

			if (!isset($_POST['item']) || !is_array($_POST['item'])) {
				return false;
			}

			if (empty($_POST['item'])) {
				return false;
			}
			$g = new API_COMMENT();
			switch (strtolower($_POST['bulkaction'])) {
				case 'disapprove':
					if ($_SESSION['user']->verify('comment', 'edit')) {
						if ($g->multiUpdateField('status', 'disapproved', $_POST['item'])) {
							$GLOBALS['Message'] = MessageBox(GetLang('CommentMultiDisapproveOk'), MSG_SUCCESS);
						} else {
							$GLOBALS['Message'] = MessageBox(GetLang('CommentMultiDisapproveFail'), MSG_ERROR);
						}
					} else {
						$this->NoPermission();
						return false;
					}
				break;
				case 'approve':
					if ($_SESSION['user']->verify('comment', 'edit')) {
						if ($g->multiUpdateField('status', 'approved', $_POST['item'])) {
							$GLOBALS['Message'] = MessageBox(GetLang('CommentMultiApproveOk'), MSG_SUCCESS);
						} else {
							$GLOBALS['Message'] = MessageBox(GetLang('CommentMultiApproveFail'), MSG_ERROR);
						}
					} else {
						$this->NoPermission();
						return false;
					}
				break;
				case 'delete':
					if ($_SESSION['user']->verify('comment', 'delete')) {
						if ($g->multiDelete($_POST['item'])) {
							$GLOBALS['Message'] = MessageBox(GetLang('CommentMultiDeleteOk'), MSG_SUCCESS);
						} else {
							$GLOBALS['Message'] = MessageBox(GetLang('CommentMultiDeleteFail'), MSG_ERROR);
						}
					} else {
						$this->NoPermission();
						return false;
					}
				break;
			}
		}

		/**
		* GetStatusOptions
		* Get html options for displaying comment statuses
		*
		* @param string $cur the current status
		*
		* @return string the html for the options
		*/
		function GetStatusOptions($cur)
		{
			$str = '';
			$status = array (
				'approved',
				'pending',
				'disapproved',
			);

			foreach ($status as $s) {
				$langStr = ucwords($s);
				$str .= '<option value="'.$s.'"'.(($cur == $s) ? ' selected' : '').'>'.$GLOBALS['AKB_LANG'][$langStr].'</option>';
			}

			return $str;
		}

		/**
		* UpdateStatus
		* Update the status of a comment
		*
		* @return void
		*/
		function UpdateStatus()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('comment', 'edit')) {
				$this->NoPermission();
				return;
			}

			$newStatus = "";
			$msg = "";

			if (isset($_GET["commentId"]) && isset($_GET["status"])) {
				$commentId = $_GET["commentId"];
				$status = $_GET["status"];

				switch ($status) {
					case 1:
						$newStatus = "approved";
						$msg = GetLang("CommentApproved");
						break;
					case 2:
						$newStatus = "disapproved";
						$msg = GetLang("CommentDisapproved");
						break;
				}

				$query = sprintf("update %scomments set status='%s' where commentid='%d'", $GLOBALS["tablePrefix"], $GLOBALS['AKB_DB']->Quote($newStatus), $commentId);
				$GLOBALS['AKB_DB']->Query($query);

				$this->ShowCommentList($msg, MSG_SUCCESS);
			} elseif(isset($_POST['comment']) && is_array($_POST['comment'])) {
				$status = ($_POST['action'] == 'Approve Selected') ? 'approved' : 'disapproved';

				// Make sure we only deal with ints
				foreach (array_keys($_POST['comment']) as $comment) {
					$commentIds[] = (int) $comment;
				}
				$query = sprintf("update %scomments set status='%s' where commentid IN (%s)", $GLOBALS["tablePrefix"], $GLOBALS['AKB_DB']->Quote($status), implode(', ', $commentIds));
				$GLOBALS['AKB_DB']->Query($query);
				$this->ShowCommentList($msg, MSG_SUCCESS);
			} else {
				$this->ShowCommentList();
			}
		}

		/**
		* DeleteComment
		* Delete a comment from the database
		*
		* @return void
		*/
		function DeleteComment()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('comment', 'delete')) {
				$this->NoPermission();
				return;
			}

			if (isset($_GET["commentId"])) {
				$commentId = $_GET["commentId"];
				$c = new API_COMMENT();
				$c->delete($commentId);

				$this->ShowCommentList(GetLang("CommentDeletedSuccessfully"), MSG_SUCCESS);
			} elseif(isset($_POST['comment']) && is_array($_POST['comment'])) {
				$c = new API_COMMENT();
				// Make sure we only deal with ints
				foreach (array_keys($_POST['comment']) as $comment) {
					$c->delete($comment);
				}
				$this->ShowCommentList(GetLang("CommentDeletedSuccessfully"), MSG_SUCCESS);
			} else {
				$this->ShowCommentList();
			}
		}

		/**
		* PreviewComment
		* Show the preview a comment popup window
		*
		* @return void
		*/
		function PreviewComment()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('comment', 'edit')
			&& !$_SESSION['user']->verify('comment', 'delete')) {
				$this->NoPermission();
				return;
			}

			if (isset($_GET["commentId"])) {
				$commentId = $_GET["commentId"];
				$query = sprintf("select * from %scomments where commentid='%d'", $GLOBALS["tablePrefix"], $commentId);
				$commentResult = $GLOBALS['AKB_DB']->Query($query);

				if ($commentRow = $GLOBALS['AKB_DB']->Fetch($commentResult)) {
					// Preview a comment
					$GLOBALS["Comment"] = nl2br(htmlspecialchars($commentRow["content"], ENT_QUOTES, $GLOBALS['charset']));
					$GLOBALS["Author"] = $commentRow["name"];

					if (!empty($commentRow["email"])) {
						$GLOBALS["Author"] .= sprintf(" (<a href='mailto:%s'>%s</a>)", htmlspecialchars($commentRow["email"], ENT_QUOTES, $GLOBALS['charset']), htmlspecialchars($commentRow["email"], ENT_QUOTES, $GLOBALS['charset']));
					}

					$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("comment.preview");
					$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
				} else {
					echo '<script language="javascript" type="text/javascript">window.close();</script>';
				}
			} else {
				echo '<script language="javascript" type="text/javascript">window.close();</script>';
			}
		}

		/**
		* ShowCommentList
		* Show the list of comments
		*
		* @param string $MsgDesc The message to display
		* @param int $MsgStatus The status of the message
		*
		* @return void
		*/
		function ShowCommentList($MsgDesc = "", $MsgStatus = "")
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('comment', 'edit')
			&& !$_SESSION['user']->verify('comment', 'delete')) {
				$this->NoPermission();
				return;
			}
			// Show a list of comments to edit/delete
			$page = 0;
			$start = 0;
			$numComments = 0;
			$numpages = 0;
			$GLOBALS['Grid'] = '';
			$GLOBALS['CommentBulkOptions'] = '';
			$GLOBALS['HideHeading'] = '';

			$this->InitAdvancedSearch();

			$GLOBALS['SearchQuery'] = $_SESSION['comment_search']['q'];
			
			$_SESSION['comment_sort']['sortfield'] = "posted";
			$_SESSION['comment_sort']['sortorder'] = "DESC";

			if (isset($_GET['sortfield']) && isset($_GET['sortorder'])) {
				$_SESSION['comment_sort']['sortfield'] = $_GET['sortfield'];
				$_SESSION['comment_sort']['sortorder'] = $_GET['sortorder'];
			}
			
			$this->BuildListQueries();

			$sortURL = sprintf('&amp;sortfield=%s&amp;sortorder=%s', $_SESSION['comment_sort']['sortfield'], $_SESSION['comment_sort']['sortorder']);

			if ($MsgDesc != '') {
				$GLOBALS["Message"] = MessageBox($MsgDesc, $MsgStatus);
			}

			if ($_SESSION['user']->verify('comment', 'delete')) {
				$GLOBALS['CommentBulkOptions'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('CommentBulkDeleteOptions');
			}

			if ($_SESSION['user']->verify('comment', 'edit')) {
				$GLOBALS['ShowCreateButton'] = 'inline';
				$GLOBALS['CommentBulkOptions'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('CommentBulkEditOptions');
			} else {
				$GLOBALS['ShowCreateButton'] = 'none';
			}

			// {{{ Setup our paging
			// What page are we on ?
			$page = isset($_GET['page'])? (int) $_GET['page'] : 1;

			// What is our offset in the results for the start ?
			$start = ($page == 1) ? 0 : ($page * AKB_COMMENT_PER_PAGE) - (AKB_COMMENT_PER_PAGE-1) -1;

			// }}}

			// {{{ Build the alpha list (A-Z box list)
			$GLOBALS['FormAction'] = $GLOBALS['pathToKB'].'/admin/index.php?ToDo=viewComments';
			$GLOBALS["AlphaList"] = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListHeader');
			$GLOBALS["Item"] = 'comments';
			$letters = GetAlphaList();
			foreach ($letters as $letter) {
				$GLOBALS['Letter'] = $letter;
				$GLOBALS['TermClickLetter'] = sprintf(GetLang("TermClickLetter"), strtolower(GetLang('Comments')), $letter);
				if (isset($_GET['letter']) && $letter == $_GET['letter']) {
					$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListRowCurrent');
				} else {
					$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListRow');
				}
			}
			$GLOBALS["AlphaList"] .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('AlphaListFooter');
			// }}

			$commentResult = $GLOBALS['AKB_DB']->Query($this->query);

			// How many search terms do we have in total ?
			$numComments = $GLOBALS['AKB_DB']->FetchOne($this->countQuery);
			$numpages = ceil($numComments / AKB_COMMENT_PER_PAGE);
			$link = 'index.php?ToDo=viewComments';

			$GLOBALS['Nav'] = BuildNav($link, $numpages, $page);
			
			if ($GLOBALS['AKB_DB']->CountResult($this->query)) {
				$GLOBALS["StatusSortUpLink"] = "index.php?ToDo=viewComments&amp;sortfield=status&amp;sortorder=asc";
				$GLOBALS["StatusSortDownLink"] = "index.php?ToDo=viewComments&amp;sortfield=status&amp;sortorder=desc";

				$GLOBALS["DateSortUpLink"] = "index.php?ToDo=viewComments&amp;sortfield=posted&amp;sortorder=asc";
				$GLOBALS["DateSortDownLink"] = "index.php?ToDo=viewComments&amp;sortfield=posted&amp;sortorder=desc";

				while ($commentRow = $GLOBALS['AKB_DB']->Fetch($commentResult)) {
					$GLOBALS["CommentId"] = $commentRow["commentid"];
					$GLOBALS["Comment"] = strip_tags($commentRow["content"]);
					$GLOBALS["Question"] = $this->GetCommentQuestionLink($commentRow["questionid"], $commentRow['title']);
					$GLOBALS["DateAdded"] = date("jS F Y", strtotime($commentRow["posted"]));

					if ($_SESSION['user']->verify('comment', 'edit')) {
						$GLOBALS['Edit'] = '<a href="index.php?ToDo=editComment&amp;commentId='.$commentRow["commentid"].'">'.GetLang('Edit').'</a>';
						$GLOBALS['Approve'] = '<a href="index.php?ToDo=updateCommentStatus&amp;status=1&amp;commentId='.$commentRow["commentid"].'">'.GetLang('Approve').'</a>';
						$GLOBALS['Disapprove'] = '<a href="index.php?ToDo=updateCommentStatus&amp;status=2&amp;commentId='.$commentRow["commentid"].'">'.GetLang('Disapprove').'</a>';
						$GLOBALS['Delete'] = '<a href="index.php?ToDo=deleteComment&amp;commentId='.$commentRow["commentid"].'">'.GetLang('Delete').'</a>';
						$GLOBALS['Delete'] = '<a href="#" onclick="if(confirm(\''.GetLang('ConfirmDeleteComment').'\')){window.location=\'index.php?ToDo=deleteComment&amp;commentId='.$commentRow["commentid"].'\'}">'.GetLang('Delete').'</a>';
					} else {
						$GLOBALS['Edit'] = '<span class="Disabled">'.GetLang('Edit').'</span> ';
						$GLOBALS['Approve'] = '<span class="Disabled">'.GetLang('Approve').'</span> ';
						$GLOBALS['Disapprove'] = '<span class="Disabled">'.GetLang('Disapprove').'</span> ';
						$GLOBALS['Delete'] = '<span class="Disabled">'.GetLang('Delete').'</span> ';
					}

					$GLOBALS['Status'] = GetLang(ucfirst($commentRow['status']));
					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('comment.row');
					$GLOBALS['Grid'] .= $GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate(true);
				}

				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('comment.manage');
				$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
			} else {
				if (isset($_SESSION['comment_search']['searching'])) {
					// No comments found when searching
					$GLOBALS['Title'] = GetLang('ManageQuestions');
					$GLOBALS['ManageQuestMessage'] = GetLang('ManageQuestMessage');
					$GLOBALS['ButtonText'] = GetLang('CreateQuestion');
					$GLOBALS['ButtonClass'] = 'Field150';
					$GLOBALS['Message'] .= MessageBox(GetLang('NoCommentSearch'), MSG_WARNING);
					$GLOBALS['URL'] = 'index.php?ToDo=createQuestion';
					$GLOBALS['HideHeading'] = 'style="display:none"';
					$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('comment.manage');
					$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
				} else {
					$GLOBALS["Title"] = GetLang("ManageComments");
					$GLOBALS["Style"] = "display:none";
					$GLOBALS["ButtonClass"] = "Field150";
					$GLOBALS["Message"] .= '<br />'.MessageBox(GetLang("NoComments"), MSG_SUCCESS);
					$GLOBALS["URL"] = "index.php?ToDo=createQuestion";

					$GLOBALS["AKB_CLASS_TEMPLATE"]->SetTemplate("message");
					$GLOBALS["AKB_CLASS_TEMPLATE"]->ParseTemplate();
				}
			}
		}

		/**
		* GetCommentQuestionLink
		* Get the html comment to the question the comment was in response to
		*
		* @param int $qid the question id to create the link to
		* @param string $title The title of the question
		*
		* @return string The html for the link
		*/
		function GetCommentQuestionLink($qid, $title)
		{
			if ($qid == 0) {
				return GetLang('NA');
			} else {
				$link = sprintf('<a href="%s" target="_blank">%s</a>', GetUrl('question', $qid), htmlspecialchars($title, ENT_QUOTES, $GLOBALS['charset']));
				return $link;
			}
		}

		/**
		* EditComment
		* Show the page to edit a comment
		*
		* @return void
		*/
		function EditComment()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('comment', 'edit')) {
				$this->NoPermission();
				return;
			}

			$arrComment = array();
			// Show the form to edit a comment

			if (isset($_GET["commentId"])) {
				$commentId = (int) $_GET["commentId"];
				$query =  sprintf("select * from %scomments where commentid='%d'", $GLOBALS["tablePrefix"], $commentId);
				$result = $GLOBALS['AKB_DB']->Query($query);
				$arrComment = $GLOBALS['AKB_DB']->Fetch($result);
			}

			if (!empty($arrComment) && isset($_GET['commentId'])) {
				$GLOBALS['Name']			= htmlspecialchars($arrComment['name'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['Email']			= htmlspecialchars($arrComment['email'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['Comment']			= htmlspecialchars($arrComment['content'], ENT_QUOTES, $GLOBALS['charset']);
				$GLOBALS['CommentId']		= $commentId;
				$status						= $arrComment['status'];
				$GLOBALS['StatusOptions']	= $this->GetStatusOptions($status);

				$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('comment.form');
				$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
			} else {					// Setup the stats values
				if (isset($commentRow["status"])) {
					if ($commentRow["status"] == "pending") {
						$GLOBALS["Approve"] = sprintf("<a href='index.php?ToDo=updateCommentStatus&amp;commentId=%d&amp;status=1'>%s</a>", $commentRow["commentid"], GetLang("Approve"));
						$GLOBALS["Disapprove"] = sprintf("<a href='index.php?ToDo=updateCommentStatus&amp;commentId=%d&amp;status=2'>%s</a>", $commentRow["commentid"], GetLang("Disapprove"));
					} else if ($commentRow["status"] == "approved") {
						$GLOBALS["Approve"] = sprintf("<span class=\"disabled\"><u>%s</u></span>", GetLang("Approve"));
						$GLOBALS["Disapprove"] = sprintf("<a href='index.php?ToDo=updateCommentStatus&amp;commentId=%d&amp;status=2'>%s</a>", $commentRow["commentid"], GetLang("Disapprove"));
					} else {
						// Disapproved
						$GLOBALS["Approve"] = sprintf("<a href='index.php?ToDo=updateCommentStatus&amp;commentId=%d&amp;status=1'>%s</a>", $commentRow["commentid"], GetLang("Approve"));
						$GLOBALS["Disapprove"] = sprintf("<span class=\"disabled\"><u>%s</u></span>", GetLang("Disapprove"));
					}
				}
				$this->ShowCommentList();
			}
		}

		/**
		* SaveUpdatedComment
		* Update a comment in the database
		*
		* @return void
		*/
		function SaveUpdatedComment()
		{
			// Check they have permission to be here
			if (!$_SESSION['user']->verify('comment', 'edit')) {
				$this->NoPermission();
				return;
			}

			$dataValue = array(
			'name' => $_POST['fromname'],
			'email' => $_POST['fromemail'],
			'content' => $_POST['comment'],
			'status' => $_POST['status']
			);
			$where = sprintf(" commentid='%d'", (int) $_POST['commentid']);
			
			if ($GLOBALS['AKB_DB']->UpdateQuery($GLOBALS['tablePrefix'].'comments', $dataValue, $where)) {
				$this->ShowCommentList(GetLang("CommentUpdateSuccess"), MSG_SUCCESS);
			} else {
				$this->ShowCommentList(GetLang("CommentUpdateFail"), MSG_FAILED);
			}
		}

		/**
		* ShowAdvancedSearch
		*
		* Show the advanced search page
		*
		* @return void
		*/
		function ShowAdvancedSearch()
		{
			$this->InitAdvancedSearch();

			$GLOBALS['FormAction']		= $GLOBALS['pathToKB'].'/admin/index.php?ToDo=viewComments';
			$GLOBALS['CategoryOptions']	= $GLOBALS['AKB_CLASS_CATEGORY']->GetCategoryOptions($_SESSION['comment_search']['categories']);
			$GLOBALS['postedOp']	= $GLOBALS['AKB_CLASS_HELPER']->getDateCompareOptions($_SESSION['comment_search']['postedop']);
			$status_checked = 'Status'.ucfirst($_SESSION['comment_search']['status']).'Checked';
			$GLOBALS[$status_checked] 	= 'selected';

			$GLOBALS['status']		= $_SESSION['comment_search']['status'];
			$GLOBALS['posted'] = $_SESSION['comment_search']['posted'];
			if (!empty($_SESSION['comment_search']['posted'])) {
				$GLOBALS['jsPosted'] = "'".str_replace("-", "','", $_SESSION['comment_search']['posted'])."'";
			} else {
				$GLOBALS['jsPosted'] = '';
			}
			$GLOBALS['SearchQuery']	= $_SESSION['comment_search']['q'];
			$GLOBALS['SortField']	= $_SESSION['comment_sort']['sortfield'];
			$GLOBALS['SortOrder']	= $_SESSION['comment_sort']['sortorder'];

			$GLOBALS['AKB_CLASS_TEMPLATE']->SetTemplate('comment.advancedsearch');
			$GLOBALS['AKB_CLASS_TEMPLATE']->ParseTemplate();
		}

		/**
		* InitAdvancedSearch
		*
		* Sets up the session vars to control searching and sorting for the page
		* that displays the list of questions.
		*
		* @return void
		*/
		function InitAdvancedSearch()
		{
			// Define the vars we want to keep track of related to searching
			// and sorting
			$search_settings = array (
				'q'				=> '',
				'categories'	=> array('-1'),
				'postedop'	=> '>=',
				'posted'	=> '',
				'status'		=> 'all',
				'letter'		=> '',
			);
			$sort_settings = array (
				'sortfield'		=> 'status',
				'sortorder'		=> 'asc',
			);

			if (isset($_GET['resetsearch'])) {
				unset($_SESSION['comment_search']);
			}

			if (!isset($_SESSION['comment_sort']['sortfield'])
				|| !isset($_SESSION['comment_sort']['sortorder'])
				|| isset($_GET['sortfield'])
				|| isset($_GET['sortorder'])) {
				foreach ($sort_settings as $k => $v) {
					if (!empty($_GET) && isset($_GET[$k])) {
						$validate_function = 'validate_'.$k;
						if (method_exists($this, $validate_function)
							&& $this->$validate_function($_GET[$k])) {
							$_SESSION['comment_sort'][$k] = $_GET[$k];
						} elseif (method_exists($this, $validate_function)) {
							$_SESSION['comment_sort'][$k] = $v;
						} else {
							$_SESSION['comment_sort'][$k] = $_GET[$k];
						}
					} else {
						$_SESSION['comment_sort'][$k] = $v;
					}
				}
			}
			// If our search settings have never been saved or settings have
			// just been submitted then set them up, otherwise we assume they
			// are already set
			if (!isset($_SESSION['comment_search'])
				|| isset($_POST['q'])
				|| !empty($_GET['letter'])) {
				foreach ($search_settings as $k => $v) {
					if (!empty($_REQUEST) && isset($_REQUEST[$k])) {
						// Only set the session var to the post var IF
						// the var doesnt have a validate function or if
						// the value passeds the validate function
						$validate_function = 'validate_'.$k;

						if (method_exists($this, $validate_function)
							&& $this->$validate_function($_REQUEST[$k])) {
								$_SESSION['comment_search'][$k] = $_REQUEST[$k];
							} elseif (method_exists($this, $validate_function)) {
								$_SESSION['comment_search'][$k] = $v;
							} else {
								$_SESSION['comment_search'][$k] = $_REQUEST[$k];
							}
					} else {
						$_SESSION['comment_search'][$k] = $v;
					}
				}
			}

			if (isset($_POST['q']) && ((isset($_POST['bulkaction']) && $_POST['bulkaction'] == '') || !isset($_POST['bulkaction']))) {
				$_SESSION['comment_search']['searching'] = true;
			}

		}

		/**
		* BuildListQueries
		*
		* Create the queries for displaying the list based on values saved in
		* the session. This function assumes that InitAdvancedSearch has been
		* called at some time in the sesison before it (not necessarily on this
		* page view).
		*
		* @return void
		*/
		function BuildListQueries()
		{
			$having = false;

			$page = isset($_GET['page'])? (int) $_GET['page'] : 1;
			$start = ($page == 1) ? 0 : ($page * AKB_COMMENT_PER_PAGE) - (AKB_COMMENT_PER_PAGE-1) -1;

			$allowedCats = $GLOBALS['AKB_CLASS_CATEGORY']->GetPermittedCats();
			$cats = array_merge($allowedCats, array_diff($_SESSION['comment_search']['categories'], array('-1')));

			// Start the query off
			if (empty($cats)) {
				$this->countQuery = "SELECT COUNT(*)\n";
				$this->countQuery .= "FROM ";
			} else {
				$this->countQuery = "SELECT COUNT(DISTINCT c.commentid) FROM ";
			}
			
			
			

			$this->query = "SELECT commentid, c.questionid, status, posted, title, content ";
			$this->query .= "from ".$GLOBALS['tablePrefix']."comments c, ".$GLOBALS['tablePrefix']."questions q ";

			
			
			$this->query .= "WHERE commentid IN ";
			$this->query .= "(";
			$this->query .= "SELECT DISTINCT commentid";
			$this->query .= "\n";
			$this->query .= "FROM ";

			// Work out which tables we need
			if (empty($cats)) {
				$this->countQuery .= $GLOBALS['tablePrefix']."questions q,";
				$this->countQuery .= $GLOBALS['tablePrefix']."comments c \n";
			} else {
				$this->countQuery .= $GLOBALS['tablePrefix']."questions q, ";
				$this->countQuery .= $GLOBALS['tablePrefix']."comments c, ";
				$this->countQuery .= $GLOBALS['tablePrefix']."categoryassociations a\n";
			}

			$this->query .= $GLOBALS['tablePrefix']."comments c, ".$GLOBALS['tablePrefix']."questions q ";

			if (!empty($cats)) {
				$this->query .= " LEFT OUTER JOIN ".$GLOBALS['tablePrefix']."categoryassociations a ";
				$this->query .= "ON a.questionid = q.questionid\n";
			}

			$this->countQuery .= "WHERE c.questionid = q.questionid\n";
			$this->query .= "WHERE c.questionid = q.questionid\n";

			// Limit results to a particular question
			if(!empty($_SESSION['comment_search']['questionid']))
			{
				$questionid = (int)$_SESSION['comment_search']['questionid'];
				$this->countQuery .= " AND c.questionid=".$questionid."\n";
				$this->query .= " AND c.questionid=".$questionid."\n";
			}
			else if(!empty($_GET['questionid']))
			{
				$questionid = (int)$_GET['questionid'];
				$this->countQuery .= " AND c.questionid=".$questionid."\n";
				$this->query .= " AND c.questionid=".$questionid."\n";
			}

			if (!empty($_SESSION['comment_search']['q'])) {
				$this->countQuery .= "AND (title like '%".$GLOBALS['AKB_DB']->Quote($_SESSION['comment_search']['q'])."%'";
				$this->countQuery .= " OR content like '%".$GLOBALS['AKB_DB']->Quote($_SESSION['comment_search']['q'])."%')\n";
				$this->query .= "AND (title like '%".$GLOBALS['AKB_DB']->Quote($_SESSION['comment_search']['q'])."%'";
				$this->query .= " OR content like '%".$GLOBALS['AKB_DB']->Quote($_SESSION['comment_search']['q'])."%')\n";
			}

			if (!empty($_SESSION['comment_search']['postedop']) && !empty($_SESSION['comment_search']['posted']) ) {
				$this->countQuery .= "AND posted ".$_SESSION['comment_search']['postedop']." '".$GLOBALS['AKB_DB']->Quote($_SESSION['comment_search']['posted'])."'\n";
				$this->query .= "AND posted ".$_SESSION['comment_search']['postedop']." '".$GLOBALS['AKB_DB']->Quote($_SESSION['comment_search']['posted'])."'\n";
			}

			if (!empty($cats)) {
				$catString = implode(', ', $cats);
				$this->countQuery .= "AND categoryid IN (".$catString.")\n";
				$this->query .= "AND categoryid IN (".$catString.")\n";
			}

			if (in_array($_SESSION['comment_search']['status'], array('approved', 'disapproved', 'pending'))) {
				$this->countQuery .= "AND status = '".$_SESSION['comment_search']['status']."'\n";
				$this->query .= "AND status = '".$_SESSION['comment_search']['status']."'\n";
			}
			$this->query .= ") ";
			$this->query .= "AND c.questionid = q.questionid ";
			$this->query .= "ORDER BY ".$GLOBALS['AKB_DB']->Quote($_SESSION['comment_sort']['sortfield'])." ".$GLOBALS['AKB_DB']->Quote($_SESSION['comment_sort']['sortorder'])."\n";
			$this->query .= $GLOBALS['AKB_DB']->AddLimit($start, AKB_COMMENT_PER_PAGE);

		}

		/**
		* validate_postedop
		* Validate that the posted op submitted is valid
		*
		* @param string $var The op to validate
		*
		* @return bool Is it valid ?
		*/
		function validate_postedop($var)
		{
			$valid_ops = array ('>', '<', '=', '<=', '>=');
			return in_array($var, $valid_ops);
		}

		/**
		* validate_posted
		* Validate that the value of posted is valid
		*
		* @param string $var The date to check
		*
		* @return bool Is it valid ?
		*/
		function validate_posted($var)
		{
			// Split the date into its parts
			$matches = array();
			preg_match('/^(\d{4})\-(\d{1,2})\-(\d{1,2})$/', $var, $matches);
			if (count($matches) <> 4) {
				return false;
			}
			$year = $matches[1];
			$month = $matches[2];
			$day = $matches[3];

			// Make sure the parts are ints
			if ((int) $year != $year) {
				return false;
			}
			if ((int) $month != $month) {
				return false;
			}
			if ((int) $day != $day) {
				return false;
			}

			// Make sure the month is valid
			if ($month > 12) {
				return false;
			}
			if ($month < 1) {
				return false;
			}

			// Make sure the day is valid
			if ($day < 1) {
				return false;
			}

			// Check the day to make sure its not bigger then that last of the month
			if ($day > date('t', mktime(0,0,0,$month,1,$year))) {
				return false;
			}
			return true;
		}

		/**
		* validate_status
		* Ensure the value of status is valid
		*
		* @param string $var The value to check
		*
		* @return bool Is it valid ?
		*/
		function validate_status($var)
		{
			$valid_vars = array('approved', 'disapproved', 'pending', 'all');
			return in_array($var, $valid_vars);
		}

		/**
		* validate_sortorder
		* Ensure the sort order is valid
		*
		* @param The value to check
		*
		* @return bool Is it valid ?
		*/
		function validate_sortorder($var)
		{
			return ($var == 'asc' || $var == 'desc' || $var == '');
		}

		/**
		* validate_sortfield
		* Ensure the field the user wants to sort on is valid
		*
		* @param string $var the field to sort on
		*
		* @return bool Is it valid ?
		*/
		function validate_sortfield($var)
		{
			$valid_fields = array ('status', 'posted', 'content');
			return in_array($var, $valid_fields);
		}

	}

?>